import React, { useEffect, useRef, useState } from 'react';
import {
  ProForm,
  ProFormDigit,
  ProFormText,
  ProFormRadio,
  ProFormTextArea,
  ProFormSelect,
  ProFormDateTimePicker,
  ProFormInstance
} from '@ant-design/pro-components';
import { Form, message, Modal, Progress, Slider } from 'antd';
import { useIntl, FormattedMessage, useModel, useAccess} from '@umijs/max';
import { getAssetList ,getDeviceNumsByName} from '@/services/manage/asset';
import { getFaultList ,getFaultTypes ,getFaultNames} from '@/services/manage/fault';
import {getdeviceNames} from '@/services/manage/asset';
export type FaultFormData = Record<string, unknown> & Partial<API.Manage.Fault>;

export type AlarmFormProps = {
  onCancel: (flag?: boolean, formVals?: FaultFormData) => void;
  onSubmit: (values: FaultFormData) => Promise<void>;
  open: boolean;
}

const AlarmForm: React.FC<AlarmFormProps> = (props) => {
  const {onCancel, onSubmit, open} = props;
  const [form] = Form.useForm();
  const [deviceNums, setDeviceNums] = useState<string[]>([]);
  const [faultTypes, setFaultTypes] = useState<string[]>([]);
  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser; 
  const [deviceNames, setDeviceNames] = useState<string[]>([]);
  const access = useAccess();
  // const form = useRef<ProFormInstance>();
  //获取设备名称
  const allDeviceNames = async () =>{
    try{
      if(access.hasPerms('inspection:asset:allDeviceName')){
        const deviceNames = await getdeviceNames();
        const deviceNameList = Array.isArray(deviceNames?.rows) ? deviceNames.rows : [];
        setDeviceNames(deviceNameList);
      }
    }
    catch(error){
      message.error('获取设备名称失败:');
      setDeviceNames([]);
    }
  }
  
  //获取故障类型
  const FaultTypes = async () => { 
    try{
      if(access.hasPerms('inspection:faultType:allTypeName')){
        const types = await getFaultNames()  
        const typeList = Array.isArray(types?.rows) ? types.rows : [];
        setFaultTypes(typeList)
      }
    }
    catch(error){
      message.error('获取故障类型失败:');
      setFaultTypes([]);
    }
  }

  useEffect(() => { 
    form.resetFields();
    allDeviceNames();
    FaultTypes();
  }, [form, props]);



  const handleFinish = async (values: Record<string, any>) => {

    const FaultFormData = {
      ...values,
      currentStatus: 0, // 默认未处理
      reporter: currentUser?.nickName, // 默认处理人为空
      userId: currentUser?.userId,
    }
    console.log(FaultFormData);
    onSubmit(FaultFormData); // 提交表单数据
  };

  return (
    <Modal
      width={640}
      title='新增告警'
      forceRender
      open={open}
      onOk={()=>form.submit()} // 触发表单提交
      onCancel={()=>onCancel()} // 关闭模态框
    >
      <ProForm
        form={form}
        grid={true}
        layout="horizontal"
        submitter={false}
        onFinish={handleFinish} // 处理表单提交
        initialValues={{
          date: Date.now(),
          time: Date.now(),
        }}>
        <ProFormSelect
          name="deviceName"
          label='设备名称'
          options={deviceNames}
          placeholder="请选择设备名称"
          rules={[{ required: true, message: '请选择设备名称!' }]}
          onChange={async (value: string | undefined) => {
            if (value && access.hasPerms('inspection:asset:deviceNums')) {
              const deviceNum = await getDeviceNumsByName(value);
              setDeviceNums(deviceNum?.rows);
            } else {
              // 清空设备编号选项和字段值
              setDeviceNums([]);
              form.setFieldsValue({ deviceNum: undefined });
            }
          }}
        />
        <ProFormSelect
          name="deviceNum"
          label='设备编号'
          placeholder="请输入设备编号"
          options={deviceNums}
          rules={[
            {
              required: true,
              message:"请输入设备编号!",
            },           
          ]}
        />
        <ProFormRadio.Group
          // valueEnum={alarmLevel}//alarmLevel键必须为string类型
          name="faultLevel"
          options={[
            { label: '严重', value: 1 },
            { label: '中等', value: 2 },
            { label: '轻度', value: 3 },
          ]}
          label='故障等级'
          placeholder="请选择故障等级"
          rules={[
            {
              required: true,
              message:"请选择故障等级！",
            },
          ]}
          fieldProps = {{
            defaultValue: "3"
          }}
        /> 
        <ProFormSelect
          name = "faultType"
          label='故障类型'
          options={faultTypes}
          placeholder="请选择故障类型"
          rules={[{ required: true, message: '请选择故障类型!' }]}
        />
        <ProFormTextArea
          name="description"
          label="故障描述"
          placeholder="请填写故障详情"
        />
        <ProFormDateTimePicker
          name="occurrenceTime"
          label="发生时间"
          fieldProps={{
            format: 'YYYY-MM-DD HH:mm:ss',  // 可自定义时间格式
            showTime: true,
          }}
          rules={[
            {
              required: true,
              message: "请选择发生时间！" ,
            },
          ]}
        /> 
      </ProForm>
    </Modal>
  );
};

export default AlarmForm;